package com.bluefish.bltuan.action.user;

import java.text.MessageFormat;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.bluefish.bltuan.action.AbstractAction;
import com.bluefish.bltuan.cache.ApplicationConstants;
import com.bluefish.bltuan.cache.ApplicationUtils;
import com.bluefish.bltuan.module.Category;
import com.bluefish.bltuan.module.mail.EmailTemplate;
import com.bluefish.bltuan.module.user.User;
import com.bluefish.bltuan.service.CategoryService;
import com.bluefish.bltuan.service.EmailService;
import com.bluefish.bltuan.service.SubscriberService;
import com.bluefish.bltuan.tools.ActionUtil;
import com.bluefish.bltuan.util.ActiveUtils;

@Action("customer")
@Results({ @Result(name = "succ", type = "dispatcher", location = "/page/admin/success.jsp") })
public class UserAction extends AbstractAction {
    /**
     * 
     */
    private static final long serialVersionUID = 2267356603233513670L;

    //private UserService userService;

    private CategoryService   categoryService;

    private EmailService      emailService;

    private SubscriberService subscriberService;

    private User              user;

    private List<User>        users;

    private Boolean           sub;

    private String            password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /*public void setUserService(UserService userService) {
    	this.userService = userService;
    }*/

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String destroy() {
        // TODO Auto-generated method stub
        return SUCCESS;
    }

    @Override
    public String edit() {
        this.user = this.userService.findById(getIntegerId());
        return EDIT;
    }

    @Override
    public HttpHeaders editNew() {
        return new DefaultHttpHeaders(NEW).disableCaching();
    }

    @Override
    public HttpHeaders index() {
        this.users = this.userService.getAll(getPageIndex());
        return new DefaultHttpHeaders(INDEX).disableCaching();
    }

    @Override
    public HttpHeaders show() {
        this.user = this.userService.findById(getIntegerId());
        return new DefaultHttpHeaders(SHOW).disableCaching();
    }

    private boolean isEditPwd() {
        return (this.password != null && !this.password.equals(""));
    }

    private void copyProperties(User user) {
        user.setUsername(this.user.getUsername());
        user.setPhone(this.user.getPhone());
    }

    @Override
    public String update() {
        User user = this.userService.findById(getIntegerId());
        copyProperties(user);
        if (isEditPwd())
            user.setPassword(this.password);
        this.userService.update(user);
        return SUCCESS;
    }

    @Override
    public HttpHeaders create() {
        String cityId = ActionUtil.getRequestParameter("cityId");
        Category category = this.categoryService.findById(Integer.valueOf(cityId));
        String activeCode = ActiveUtils.getActiveCode();
        this.user.setCity(category);
        this.user.setRight();
        this.user.setActiveCode(activeCode);
        this.userService.save(this.user);
        String activeLink = getActiveLink(activeCode, this.user.getEmail());
        EmailTemplate template = ApplicationUtils.get(ApplicationConstants.REGISTER_TEMPLATE);
        sendRegisterEmail(activeLink, template);
        if (this.sub != null && this.sub.booleanValue()) {
            this.subscriberService.subscribe(this.user.getEmail(), category);
        }
        return new DefaultHttpHeaders(SUCCESS).disableCaching();
    }

    private String getActiveLink(String activeCode, String username) {
        String base = "http://localhost:8080/bltuan";
        String activeLink = base + "/user/active?email={0}&code={1}";
        return MessageFormat.format(activeLink, username, activeCode);
    }

    /**
     * 异步发送注册激活邮件
     * @param template 
     */
    private void sendRegisterEmail(final String activeLink, final EmailTemplate template) {
        final EmailService emailService = this.emailService;
        final User user = this.user;
        Thread t = new Thread() {
            @Override
            public void run() {
                emailService.sendRegisterEmail(user, activeLink, template);
            }
        };
        t.start();
    }

    public List<Category> getCities() {
        return this.categoryService.listCategoryByType(CategoryService.CITY);
    }

    public String activate() {
        User user = this.userService.findById(getIntegerId());
        user.activate();
        this.userService.update(user);
        return "succ";
    }

    public String freeze() {
        User user = this.userService.findById(getIntegerId());
        user.freeze();
        this.userService.update(user);
        return "succ";
    }

    /**
     * 通过Email检查用户的唯一性
     */
    public void checkEmail() {
        String checkedEmail = ActionUtil.getRequestParameter("email");
        User user = this.userService.getByEmail(checkedEmail);
        String result = (user == null) ? "Y" : "N";
        ActionUtil.writeResponse(result);
    }

    public void checkUsername() {
        String name = ActionUtil.getRequestParameter("username");
        User user = this.userService.getByName(name);
        String result = (user == null) ? "Y" : "N";
        ActionUtil.writeResponse(result);
    }

    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    public void setSub(Boolean sub) {
        this.sub = sub;
    }

    public void setSubscriberService(SubscriberService subscriberService) {
        this.subscriberService = subscriberService;
    }
}
